<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="closeDialog">
    <el-form
      ref="form"
      :model="formDate"
      :rules="formRules"
      label-width="80px"
      :inline="false"
      size="normal"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formDate.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formDate.description" rows="2" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="btnOk">立即创建</el-button>
        <el-button @click="dialogShow = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getRoleInfoApi, addRoleApi, editRoleApi } from '@/api/setting'
export default {
  name: 'AddRole',
  data() {
    return {
      // 新增 /修改 的弹窗
      dialogShow: false,
      // 表单数据
      formDate: {
        name: '',
        description: ''
      },
      // 表单校验
      formRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.formDate.id ? '修改' : '新增'
    }
  },
  methods: {
    // 表单提交事件
    async btnOk() {
      // 1.表单校验
      try {
        this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      // 2.发请求
      // 3. 成功提示(判断是新增还是修改),有id是修改，否则是新增
      if (this.formDate.id) {
        await editRoleApi(this.formDate)
        this.$message.success('修改成功')
      } else {
        await addRoleApi(this.formDate)
        this.$message.success('新增成功')
      }

      // 4.更新列表
      this.$emit('updateList')
      // 5. 关闭弹窗
      this.dialogShow = false
    },
    // 关闭弹窗事件
    closeDialog() {
      // 清空表单内容
      this.formDate = {
        name: '',
        description: ''
      }
      // 移出表单校验
      this.$refs.form.clearValidate()
    },
    // 表单数据回显事件
    async getRoleInfo(id) {
      // 获取修改行完整的数据
      const res = await getRoleInfoApi(id)
      // 回显
      this.formDate = res
      // 打开弹框
      this.dialogShow = true
    }
  }
}
</script>

<style></style>
